package com.xiaotu.util;

/**
 * 积分k值匹配
 *
 * @author zhangxiao
 * @create 2022-04-24 15:28
 */
public class IntegralUtil {

    private static final Integer[][] INTEGRAL_ARR = {
            {Integer.MIN_VALUE, 999, 120},
            {1000, 1399, 60},
            {1400, 1799, 30},
            {1800, 1999, 25},
            {2000, 2199, 20},
            {2200, 2399, 15},
            {2400, Integer.MAX_VALUE, 10}};

    private static final Integer[][] LEVEL_ARR = {
            {100, 1},
            {200, 2},
            {300, 3},
            {400, 4},
            {500, 5},
            {600, 6},
            {700, 7},
            {800, 8},
            {900, 9},
            {1000, 10},
            {1100, 11},
            {1200, 12},
            {1300, 13},
            {1400, 14},
            {1500, 15},
            {1600, 16},
            {1700, 17},
            {1800, 18},
            {2000, 19},
            {2200, 20},
            {2400, 21}
    };

    /**
     * 二分法返回 levelVal
     *
     * @param integral 积分
     * @return
     */
    public static Integer levelVal(Integer integral) {
        int sti = 0;
        int eni = LEVEL_ARR.length - 1;
        while (true) {
            if (sti == eni) {
                if (integral.compareTo(LEVEL_ARR[sti][0]) >= 0 || sti == 0) {
                    return LEVEL_ARR[sti][1];
                } else {
                    return LEVEL_ARR[sti - 1][1];
                }
            } else if ((eni - sti) == 1) {
                int min = LEVEL_ARR[sti][0];
                int max = LEVEL_ARR[eni][0];
                if (integral < min || integral < max) {
                    return LEVEL_ARR[sti][1];
                } else {
                    return LEVEL_ARR[eni][1];
                }
            } else {
                int index = (((eni - sti) + 1) / 2) + sti;
                Integer middle = LEVEL_ARR[index][0];
                Integer levelVal = LEVEL_ARR[index][1];
                int in = integral.compareTo(middle);
                if (in > 0) {
                    if (index == LEVEL_ARR.length - 1) {
                        sti = index;
                    } else {
                        sti = index + 1;
                    }
                } else if (in < 0) {
                    if (index == 0) {
                        eni = index;
                    } else {
                        eni = index - 1;
                    }
                } else {
                    return levelVal;
                }
            }
        }
    }

    /**
     * 返回 k
     *
     * @param integral 积分
     * @return
     */
    public static Integer kVal(Integer integral) {
        for (int i = 0; i < INTEGRAL_ARR.length; i++) {
            int min = INTEGRAL_ARR[i][0];
            int max = INTEGRAL_ARR[i][1];
            int k = INTEGRAL_ARR[i][2];
            if (integral.compareTo(min) >= 0 && integral.compareTo(max) <= 0)
                return k;
        }
        return null;
    }

}
